package com.working.home.ui

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.ImageView
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.working.home.R
import com.working.home.databinding.HomeFragmentMainBinding
import com.working.home.ui.search.SearchActivity
import com.working.libbase.base.BaseFragment
import com.working.libbase.model.BannerResponse
import com.working.libbase.provider.ProjectProvider
import com.working.libbase.route.RoutePath
import com.working.libcommon.adapter.setPagingAdapter
import com.working.libcommon.exts.cast
import com.working.libcommon.exts.getString
import com.working.libcommon.exts.onClick
import com.working.libview.widget.banner.BannerFactory
import com.working.libview.widget.banner.BannerView
import org.koin.androidx.viewmodel.ext.android.viewModel

@Route(path = RoutePath.HOME.MAIN_FRAGMENT)
class HomeFragment : BaseFragment() {
    private lateinit var mBinding: HomeFragmentMainBinding
    private val mViewModel by viewModel<HomeViewModel>()

    private val articleAdapter by lazy { ArticleAdapter(mViewModel.dataSource) }

    override fun onResume() {
        super.onResume()
        activity?.title = R.string.home_module_name.getString()
        immerseColor(Color.RED)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = binding(
            inflater,
            R.layout.home_fragment_main, container
        )
        return mBinding.apply { lifecycleOwner = this@HomeFragment }.root
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        menu.add(0, R.id.action_search, 0, "搜索")
            ?.setIcon(R.drawable.ic_search)
            ?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        articleAdapter.removeAllHeaderView()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_search) {
            goSearch()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun goSearch() {
        SearchActivity.start(requireContext())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        with(mBinding) {


            val banner = BannerView(requireContext())


            mViewModel.banner.observe(viewLifecycleOwner) {
                banner.setPages(it.data, object : BannerFactory<BannerResponse> {
                    override fun createView(context: Context?): View =
                        ImageView(context)

                    override fun onBind(view: View, position: Int, data: BannerResponse?) {
                        view.cast<ImageView>()?.load(data?.imagePath)
                    }
                })
                banner.start()
            }

            rvArticle.addOnScrollListener(object :
                RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 0 && fab.visibility == View.VISIBLE) {
                        fab.visibility = View.INVISIBLE
                    } else if (dy < 0 && fab.visibility != View.VISIBLE) {
                        fab.show()
                    }
                }
            })
            fab.onClick {

                ARouter.getInstance().build(RoutePath.Project.PROVIDER).navigation()
                    ?.cast<ProjectProvider>()?.getProjectNumber()
                if (rvArticle.layoutManager?.cast<LinearLayoutManager>()
                        ?.findFirstVisibleItemPosition() ?: 0 > 20
                ) {
                    rvArticle.scrollToPosition(0)
                } else {
                    rvArticle.smoothScrollToPosition(0)
                }
            }
            rvArticle.setPagingAdapter(
                viewLifecycleOwner,
                articleAdapter.apply {
                    addHeaderView(banner)
                })
        }
    }
}